package com.yanqu.road.server.manager.activity.langyabang;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.langyabang.config.*;
import com.yanqu.road.entity.activity.langyabang.entity.LangYaValueByRank;
import com.yanqu.road.entity.config.system.NormalWeightItem;
import com.yanqu.road.entity.enums.activity.langyabang.eLangYaBangEventType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.activity.LangYaBangBusiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.helper.WeightHelper;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class CrossLangYaBangConfigMgr {

    private static Logger logger = LogManager.getLogger(CrossLangYaBangConfigMgr.class.getName());

    private static Map<Integer, LangYaBangConfig> configMap = new ConcurrentHashMap<>();

    private static Random random = new Random();

    public static synchronized void reloadConfig(){

        logger.info("start reload LangYaBang activity config start");
        String nowTimeStr = DateHelper.getCurrentDateTimeString();
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(eActivityType.LangYaBang.getValue());

        Map<Integer, ActivityInfo> tempActivityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMap(activityTypeList, nowTimeStr);
        List<ActivityInfo> activityInfoList = new ArrayList<>();
        for (ActivityInfo activityInfo : tempActivityInfoMap.values()) {
            Map<Integer, UnionActivityGroup> activityGroupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            if (null != activityGroupMap) {
                for (UnionActivityGroup activityGroup : activityGroupMap.values()) {
                    if (activityGroup.getCrossServerId() == CrossBaseServer.getInstance().getServerId()){
                        activityInfoList.add(activityInfo);
                        break;
                    }
                }
            }
        }
        for (ActivityInfo activityInfo: activityInfoList){
            reloadConfig(activityInfo);
        }
        logger.info("start reload LangYaBang activity config  end");
    }

    public static synchronized void reloadConfig(ActivityInfo activityInfo){
        List<Integer> activityIdList = new ArrayList<>();
        int activityId = activityInfo.getActivityId();
        activityIdList.add(activityId);
        //事件的读进来跨服其实没用 后面看看删不删
        Map<Integer, LangYaCaseConfig> tmpCaseConfig = LangYaBangBusiness.getLangYaCaseConfigMap(activityId);
        Map<Integer,Map<Integer, LangYaCaseEventConfig>> tmpCaseEventConfig = LangYaBangBusiness.getLangYaCaseEventConfigMap(activityId);
        //区域配置
        Map<Integer,Map<Integer, LangYaBangAreaConfig>> areaConfigMap = LangYaBangBusiness.getLangYaBangAreaConfigMap(activityId);
        //总等级配置
        Map<Integer, LangYaBangBuildingConfig> buildingLevelConfigMap = LangYaBangBusiness.getLangYaBangBuildingConfigMap(activityId);
        //pve
        Map<Integer, LangYaBangPveConfig> pveConfigMap = LangYaBangBusiness.getLangYaBangPveConfigList(activityId);
        //求策
        Map<Integer,Map<Integer,LangYaRollDiceConfig>> rollDiceConfigMap= LangYaBangBusiness.getLangYaRollDiceConfigMap(activityId);
        //其他
        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityId);

        LangYaBangConfig config = new LangYaBangConfig(activityInfo,tmpCaseConfig,tmpCaseEventConfig,activityConfigMap,areaConfigMap,buildingLevelConfigMap,pveConfigMap,rollDiceConfigMap);
        configMap.put(activityId,config);
    }

    public static Map<Integer, LangYaBangConfig> getConfigMap() {
        return configMap;
    }

    public static LangYaBangConfig getConfig(int activityId){
        return configMap.get(activityId);
    }

    public static Map<Integer,Integer> getInitDrawMap(int activityId){
        Map<Integer,Integer> map = new ConcurrentHashMap<>();
        LangYaBangConfig config = configMap.get(activityId);
        Map<Integer, Map<Integer, LangYaRollDiceConfig>> rollDiceConfigMap = config.getRollDiceConfigMap();
        for (Map<Integer, LangYaRollDiceConfig> typeMap : rollDiceConfigMap.values()){
            for (LangYaRollDiceConfig diceConfig:typeMap.values()){
                if (diceConfig.getType() != eLangYaBangEventType.declareWarPvp.getValue()){
                    if (diceConfig.getProtectNum()!=-1){
                        map.put(diceConfig.getId(),0);
                    }
                }
            }
        }
        return map;
    }

    public static Map<Integer,Integer> getInitBuildingMap (int activityId){
        Map<Integer,Integer> map = new ConcurrentHashMap<>();
        LangYaBangConfig config = configMap.get(activityId);
        if (config == null){
            return map;
        }
        Map<Integer, Map<Integer, LangYaBangAreaConfig>> areaConfigMap = config.getAreaConfigMap();


        for (Map.Entry<Integer, Map<Integer, LangYaBangAreaConfig>> entry: areaConfigMap.entrySet()){
            for (LangYaBangAreaConfig areaConfig:entry.getValue().values()){
                if (areaConfig.getLv() == 0){
                    map.put(entry.getKey(),areaConfig.getAreaLvId());
                }
            }
        }
        return map;
    }

    public static LangYaRollDiceConfig getDiceConfigById(int activityId,int eventId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        LangYaBangConfig config = configMap.get(activityId);
        Map<Integer, Map<Integer, LangYaRollDiceConfig>> rollDiceConfigMap = config.getRollDiceConfigMap();
        for (Map<Integer, LangYaRollDiceConfig> configMap:rollDiceConfigMap.values()){
            if (configMap.containsKey(eventId)){
                return configMap.get(eventId);
            }
        }
        return null;
    }

    public static Map<Integer, Map<Integer, LangYaRollDiceConfig>> getDiceConfigMap(int activityId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        return configMap.get(activityId).getRollDiceConfigMap();
    }

    public static LangYaBangPveConfig getNpcConfig (int activityId, int npcId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        Map<Integer, LangYaBangPveConfig> pveConfigMap = configMap.get(activityId).getPveConfigMap();
        return pveConfigMap.get(npcId);
    }

    public static LangYaBangPveConfig getRandomPveConfig (int activityId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        LangYaRollDiceConfig rollDiceConfigByType = getRollDiceConfigByType(activityId, eLangYaBangEventType.pve.getValue());
        String eventParam = rollDiceConfigByType.getEventParam();
        List<String> strings = StringUtils.stringToStringList(eventParam, "\\|");
        List<NormalWeightItem> weightItems = new ArrayList<>();
        for (String string:strings){
            List<Integer> integers = StringUtils.stringToIntegerList(string, ";");
            NormalWeightItem weightItem = new NormalWeightItem();
            weightItem.setWeight(integers.get(1));
            weightItem.setValue(BigInteger.valueOf(integers.get(0)));
            weightItems.add(weightItem);
        }
        BigInteger randomValue = WeightHelper.getRandomValue(weightItems);
        int npcId = randomValue.intValue();
        return getNpcConfig(activityId,npcId);
    }

    public static LangYaBangAreaConfig getLangYaBangAreaConfig(int activityId,int areaType,int levelId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        return configMap.get(activityId).getAreaConfigMap().get(areaType).get(levelId);
    }

    public static LangYaBangAreaConfig getNextLangYaBangAreaConfig(int activityId,int areaType,int oldLevelId){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        LangYaBangConfig config = configMap.get(activityId);
        Map<Integer, LangYaBangAreaConfig> map = config.getAreaConfigMap().get(areaType);
        if (!map.containsKey(oldLevelId)){
            return null;
        }
        LangYaBangAreaConfig oldAreaConfig = map.get(oldLevelId);
        int oldLv = oldAreaConfig.getLv();

        for (LangYaBangAreaConfig areaConfig:map.values()){
            if (areaConfig.getLv() == oldLv+1){
                return areaConfig;
            }
        }
        return null;
    }

    public static LangYaRollDiceConfig getRollDiceConfigByType(int activityId,int type){
        LangYaBangConfig config = getConfig(activityId);
        if (config == null){
            return null;
        }
        Map<Integer, LangYaRollDiceConfig> integerLangYaRollDiceConfigMap = config.getRollDiceConfigMap().get(type);
        for (LangYaRollDiceConfig langYaRollDiceConfig: integerLangYaRollDiceConfigMap.values()){
            return langYaRollDiceConfig;
        }
        return null;
    }

    public static LangYaBangBuildingConfig getBuildingTotalLevelConfig(int activityId, Map<Integer,Integer>buildingLevelMap){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        int buildingTotalLevel = getBuildingTotalLevel(activityId,buildingLevelMap);
        Map<Integer, LangYaBangBuildingConfig> buildingLevelConfigMap = configMap.get(activityId).getBuildingLevelConfigMap();
        if (buildingLevelConfigMap == null){
            return null;
        }
        if (!buildingLevelConfigMap.containsKey(buildingTotalLevel)){
            return null;
        }
        LangYaBangBuildingConfig langYaBangBuildingConfig = buildingLevelConfigMap.get(buildingTotalLevel);
        return langYaBangBuildingConfig;
    }

    public static int getBuildingTotalLevelCoinAddition(int activityId, Map<Integer,Integer>buildingLevelMap){
        if (!configMap.containsKey(activityId)){
            return 0;
        }
        int buildingTotalLevel = getBuildingTotalLevel(activityId,buildingLevelMap);
        Map<Integer, LangYaBangBuildingConfig> buildingLevelConfigMap = configMap.get(activityId).getBuildingLevelConfigMap();
        if (buildingLevelConfigMap == null){
            return 0;
        }
        if (!buildingLevelConfigMap.containsKey(buildingTotalLevel)){
            return 0;
        }
        LangYaBangBuildingConfig langYaBangBuildingConfig = buildingLevelConfigMap.get(buildingTotalLevel);
        return langYaBangBuildingConfig.getEffect();
    }

    public static List<Integer> getBuildingTypeAddition(int activityId, int type, Map<Integer,Integer>buildingLevelMap){
        if (!configMap.containsKey(activityId)){
            return null;
        }
        if (!buildingLevelMap.containsKey(type)){
            return null;
        }
        int levelId = buildingLevelMap.get(type);
        LangYaBangAreaConfig langYaBangAreaConfig = getLangYaBangAreaConfig(activityId, type, levelId);
        if (langYaBangAreaConfig == null){
            return null;
        }
        return langYaBangAreaConfig.getAreaValueList();
    }

    public static int getBuildingTotalLevel(int activityId,Map<Integer,Integer>buildingLevelMap){
        if (!configMap.containsKey(activityId)){
            return 0;
        }
        int totalLevel = 0;
        for (Map.Entry<Integer,Integer> entry: buildingLevelMap.entrySet()){
            LangYaBangAreaConfig langYaBangAreaConfig = configMap.get(activityId).getAreaConfigMap().get(entry.getKey()).get(entry.getValue());
            totalLevel += langYaBangAreaConfig.getLv();
        }
        return totalLevel;
    }

    public static int getRandomAttackTime(int activityId){
        if (!configMap.containsKey(activityId)){
            return 0;
        }
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        BigInteger randomValue = WeightHelper.getRandomValue(langYaBangConfig.getNpcAttackTimeList());
        return randomValue.intValue();
    }

    public static int getRandomLoseBlood(int activityId){
        if (!configMap.containsKey(activityId)){
            return 0;
        }
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        BigInteger randomValue = WeightHelper.getRandomValue(langYaBangConfig.getNpcLossBloodList());
        return randomValue.intValue();
    }

    public static boolean checkAreaLvEnough(int activityId,Map<Integer,Integer> buildingMap,LangYaBangAreaConfig areaConfig){
        if (areaConfig.getUpLimitList() == null){
            logger.error("琅琊榜{}区域配置{}有误",areaConfig.getActivityId(),areaConfig.getAreaLvId());
            return false;
        }
        List<Integer> upLimitList = areaConfig.getUpLimitList();
        for (Map.Entry<Integer,Integer> entry : buildingMap.entrySet()){
            int limit = upLimitList.get(entry.getKey() - 1);
            LangYaBangAreaConfig langYaBangAreaConfig = CrossLangYaBangConfigMgr.getLangYaBangAreaConfig(activityId, entry.getKey(), entry.getValue());
            if (langYaBangAreaConfig == null){
                return false;
            }
            if (langYaBangAreaConfig.getLv() < limit){
                return false;
            }
        }

        return true;
    }

    public static int getEnemyUnionRankCoinAddition(int activityId,int enemyUnionRank){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return 0;
        }
        List<LangYaValueByRank> declareWarCoinAddList = langYaBangConfig.getDeclareWarCoinAddList();
        for (int i = 0; i < declareWarCoinAddList.size();i++){
            if (i == declareWarCoinAddList.size()-1){
                return declareWarCoinAddList.get(i).getValue();
            }else {
                if (declareWarCoinAddList.get(i).getMinRank() <= enemyUnionRank && enemyUnionRank < declareWarCoinAddList.get(i+1).getMinRank()){
                    return declareWarCoinAddList.get(i).getValue();
                }
            }
        }
        return 0;
    }

    public static int getEnemyUnionRankScoreAddition(int activityId,int enemyUnionRank){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return 0;
        }
        if (enemyUnionRank < 0){
            return 0;
        }
        //20230524删除积分加成 改为金币加成
        List<LangYaValueByRank> declareWarScoreAddList = langYaBangConfig.getDeclareWarCoinAddList();
        for (int i = 0; i < declareWarScoreAddList.size();i++){
            if (i == declareWarScoreAddList.size()-1){
                return declareWarScoreAddList.get(i).getValue();
            }else {
                if (declareWarScoreAddList.get(i).getMinRank() <= enemyUnionRank && enemyUnionRank < declareWarScoreAddList.get(i+1).getMinRank()){
                    return declareWarScoreAddList.get(i).getValue();
                }
            }
        }
        return 0;
    }

    public static int getMaxNoticeAndReportNum (int activityId){
        int num = 50 ;
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return num;
        }
        num = langYaBangConfig.getNoticNum();
        return num;
    }

    public static String getTokenUserRewardByOther(int activityId){
        String reward = "";
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return reward;
        }
        reward = langYaBangConfig.getTokenUserRewardByOther();
        return reward;

    }

    /**
     * 查看多倍体力消耗需要多少抽
     * @param activityId
     * @return
     */
    public static int getUsingPowerNeedDrawTime(int activityId){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return -1;
        }
        return langYaBangConfig.getDrawMultiplyLimit();
    }

    /**
     * 查看选择的体力消耗需要多少历史消耗体力
     * @param activityId
     * @param usingPower
     * @return
     */
    public static int getUsingPowerNeedHistoryUsedPower(int activityId,int usingPower){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return -1;
        }
        Map<Integer, Integer> historyUsedPowerMap = langYaBangConfig.getDrawPowerUseNeedHistoryUsedPowerMap();
        if (!historyUsedPowerMap.containsKey(usingPower)){
            return -1;
        }
        return historyUsedPowerMap.get(usingPower);
    }

    /**
     * 查看选择的体力消耗需要多少历史最高体力
     * @param activityId
     * @param usingPower
     * @return
     */
    public static int getUsingPowerNeedHistoryPower(int activityId,int usingPower){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return -1;
        }
        Map<Integer, Integer> historyHighPowerMap = langYaBangConfig.getDrawPowerUseNeedHistoryHighPowerMap();
        if (!historyHighPowerMap.containsKey(usingPower)){
            return -1;
        }
        return historyHighPowerMap.get(usingPower);
    }

    /**
     * 使用建筑判断的最大单次使用体力 暂时弃用
     * @param activityId
     * @param totalLevel
     * @return
     */
    public static int getMaxUsePowerNum(int activityId,int totalLevel){
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return 1;
        }
        Map<Integer, LangYaBangBuildingConfig> buildingLevelConfigMap = langYaBangConfig.getBuildingLevelConfigMap();
        if (!buildingLevelConfigMap.containsKey(totalLevel)){
            return 1;
        }
        return buildingLevelConfigMap.get(totalLevel).getEnergyCostChoose();

    }

    public static List<Integer> getGuideDrawList(int activityId){
        List<Integer> guideList = new ArrayList<>();
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig == null){
            return guideList;
        }
        guideList = langYaBangConfig.getGuideDrawId();
        return guideList;
    }

    public static long getRandomPvpCoinReward(int activityId,int pvpType){
        LangYaRollDiceConfig rollDiceConfigByType;

        rollDiceConfigByType = getRollDiceConfigByType(activityId, pvpType);


        if (rollDiceConfigByType == null){
            return 0;
        }
        String eventParam = rollDiceConfigByType.getBaseProduce();
        List<String> strings = StringUtils.stringToStringList(eventParam, "\\|");
        List<NormalWeightItem> weightItems = new ArrayList<>();

        for (String s:strings){
            List<Integer> integers = StringUtils.stringToIntegerList(s, ";");
            NormalWeightItem normalWeightItem = new NormalWeightItem();
            normalWeightItem.setValue(BigInteger.valueOf(integers.get(0)));
            normalWeightItem.setWeight(integers.get(1));
            weightItems.add(normalWeightItem);
        }

        BigInteger randomValue = WeightHelper.getRandomValue(weightItems);
        return randomValue.longValue();
    }

    public static boolean checkActivityCanStart(int activityId){
        if (!configMap.containsKey(activityId)){
            return false;
        }
        LangYaBangConfig langYaBangConfig = configMap.get(activityId);
        if (langYaBangConfig.getActivityInfo()==null){
            return false;
        }
        return ActivityMgr.activityInTime(langYaBangConfig.getActivityInfo());
    }

}
